package shin.test.web.service;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import shin.test.web.logic.Greeting;
import shin.test.web.logic.PMF;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Service("testGreetingOpration")
public class GreetingOprationImpl implements IGreetingOpration {

	protected final Log logger = LogFactory.getLog(getClass());
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Greeting> gets() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + Greeting.class.getName();
        List<Greeting> greetings = (List<Greeting>) pm.newQuery(query).execute();
		return greetings;
	}

	@Override
	public Greeting save(String content) {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (content == null) {
			content = "(No greeting)";
		}
		if (user != null) {
			logger.info("Greeting posted by user " + user.getNickname() + ": "
					+ content);
		} else {
			logger.info("Greeting posted anonymously: " + content);
		}
		
		Date date = new Date();
        Greeting greeting = new Greeting(user, content, date);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.makePersistent(greeting);
        } finally {
            pm.close();
        }
        return greeting;
	}

}
